/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 11:47:59
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-11 09:42:03
 * @FilePath: \keep_motion_api\models\user\userRelation.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 用户关系模型
const relationSchema = new Schema({
  follower_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  followed_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  relation_time: { type: Date, default: Date.now }
});

relationSchema.statics.getRelations = async function (follower_Name, followed_Name, offset, limit) {
  try {
    const { User } = require('./');
    const query = {};
    if (follower_Name) {
      const parentQuery = {};
      const escapedFollowerName = escapeRegex(follower_Name);
      parentQuery.name = { $regex: escapedFollowerName, $options: 'i' };
      const rows = await User.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      const follower_ids = rows.map(item => item._id);
      query.follower_id = {$in: follower_ids};
    }
    if (followed_Name) {
      const parentQuery = {};
      const escapedFollowedName = escapeRegex(followed_Name);
      parentQuery.name = { $regex: escapedFollowedName, $options: 'i' };
      const rows = await User.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      const followed_ids = rows.map(item => item._id);
      query.followed_id = {$in: followed_ids};
    }
    const aggregationPipeline = [
      // 匹配条件
      { $match: query },
      // 关联用户表，只获取 name 字段
      { $lookup: {
          from: 'users',
          localField: 'follower_id',
          foreignField: '_id',
          as: 'followerInfo'
        }
      },
      // 关联用户表，只获取 name 字段
      { $lookup: {
          from: 'users',
          localField: 'followed_id',
          foreignField: '_id',
          as: 'followedInfo'
        }
      },
      // 展开用户信息数组
      { $unwind: {
          path: '$followerInfo',
          preserveNullAndEmptyArrays: true
        }
      },
      { $unwind: {
          path: '$followedInfo',
          preserveNullAndEmptyArrays: true
        }
      },
      // 添加用户名字段（避免嵌套）
      { $addFields: {
          followerName: { $ifNull: ['$followerInfo.name', '未知用户'] },
          followedName: { $ifNull: ['$followedInfo.name', '未知用户'] }
        }
      },
      // 移除临时字段
      { $project: {
          followerInfo: 0,
          followedInfo: 0,
        }
      },
      // 分页处理
      { $skip: Number(offset || 0) },
      { $limit: Number(limit || 10) }
    ];
    const total = await this.countDocuments(query);
    const rows = await this.aggregate(aggregationPipeline);
    return { rows, total };
  } catch (error) {
    throw error;
  }
}
relationSchema.statics.createRelation = async function (follower_id, followed_id) {
  try {
    const relation = new this({follower_id, followed_id});
    return await relation.save();
  } catch (error) {
    throw error;
  }
}
relationSchema.statics.deleteRelation = async function (id) {
  try {
    return await this.findByIdAndDelete(id);
  } catch (error) {
    throw error;
  }
}
module.exports = mongoose.model('Relation', relationSchema);
